<?php
/*
 * 分站管理
 * @package    
 * @author     Mark
 * @copyright  Copyright (c) 2013 ixdcw team
 * @version    $Id: b99488aea7833d19d853b574102e3445c71e7a91 $
 */
/**
 * 分站管理
 */
class CityModule {
	var $areaid;
	var $db;
	var $table;

	/**
	 * constructor
	 * @param int $areaid
	 */
	function __construct($areaid = 0)	{
		global $db;
		$this->db = &$db;
		$this->table = Table::name(Table::NAME_CITY);
		$this->areaid = $areaid;
	}

	/**
	 * 编辑
	 * @param $post
	 * @return bool
	 */
	function edit($post) {
		if(!is_array($post)) return false;
		$post['letter'] or $post['letter'] = $this->letter($post['name']);
		$sql1 = $sql2 = $s = '';
		foreach($post as $k=>$v) {
			$sql1 .= $s.$k;
			$sql2 .= $s."'".$v."'";
			$s = ',';
		}
		$this->db->query("REPLACE INTO {$this->table} ($sql1) VALUES ($sql2)");
		return true;
	}

	/**
	 * 更新
	 * @param $post
	 * @return bool
	 */
	function update($post) {
		if(!is_array($post)) return false;
		$areaid = $post['areaid'];
		if(!$areaid) return false;
		$post['letter'] or $post['letter'] = $this->letter($post['name']);
		$sql = '';
		foreach($post as $k=>$v) {
			$sql .= ",$k='$v'";
		}
		$sql = substr($sql, 1);
		$this->db->query("UPDATE {$this->table} SET $sql WHERE areaid=$areaid");
		return true;
	}

	/**
	 * 获取一条信息
	 * @return array|void
	 */
	function get_one() {
		return $this->db->getOne("SELECT * FROM {$this->table} WHERE areaid=$this->areaid");
	}

	/**
	 * 获取列表
	 * @param $condition
	 * @return array
	 */
	function get_list($condition) {
		global $pages, $page, $pagesize, $offset, $pagesize;
		$r = $this->db->getOne("SELECT COUNT(*) AS num FROM {$this->table} WHERE $condition");
		$pages = pages($r['num'], $page, $pagesize);
		$lists = array();
		$result = $this->db->query("SELECT * FROM {$this->table} WHERE $condition ORDER BY letter,listorder LIMIT $offset,$pagesize");
		while($r = $this->db->fetchArray($result)) {
			$r['linkurl'] = SITE_URL.'city.php?action=go&forward=&areaid='.$r['areaid'];
			$lists[] = $r;
		}
		return $lists;
	}

	/**
	 * 删除
	 * @param $areaids
	 * @return bool
	 */
	function delete($areaids) {
		$areaids = is_array($areaids) ? implode(',', $areaids) : $areaids;
		$this->db->query("DELETE FROM {$this->table} WHERE areaid IN ($areaids)");
		return true;
	}

	/**
	 * 获取首字母
	 * @param $name
	 * @return string
	 */
	function letter($name) {
		return strtolower(substr(Str::text2py($name), 0, 1));
	}
}